package com.scpii.universal.pns.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.pns.dao.AppConfigsDao;
import com.scpii.universal.pns.dao.ClientUserDtoDao;
import com.scpii.universal.pns.dto.ClientUserDto;
import com.scpii.universal.pns.entity.AppConfigs;

@Service
public class AppConfigServiceImpl extends
		PnsBaseServiceImpl<ClientUserDto, Long> implements AppConfigService {

	@Resource
	private AppConfigsDao appConfigsDao;

	@Resource
	public void setBaseDao(ClientUserDtoDao clientUserDtoDao) {
		super.setBaseDao(clientUserDtoDao);
	}

	@Override
	public Map<String, String> getAllConfigs(Integer appId) {
		List<AppConfigs> configs = appConfigsDao
				.getAllConfigs(GenericConstants.APP_ID_PRE + appId);
		Map<String, String> result = null;
		if (configs != null && configs.size() != 0) {
			result = new HashMap<String, String>();
			for (AppConfigs appConfig : configs) {
				result.put(appConfig.getKey(), appConfig.getValue());
			}
		}
		return result;
	}

	@Override
	public void updateConfigs(List<AppConfigs> configs, Integer appId) {
		if (configs != null && configs.size() != 0) {
			for (AppConfigs appConfig : configs) {
				AppConfigs persistConfig = appConfigsDao
						.getByKey(GenericConstants.APP_ID_PRE + appId,
								appConfig.getKey());
				if (persistConfig != null) {
					if (StringUtils.isBlank(appConfig.getValue())) {
						appConfigsDao.delete(persistConfig);
					}
					persistConfig.setType(appConfig.getType());
					persistConfig.setValue(appConfig.getValue());
					persistConfig.setUpdateDt(new Date());
				} else {
					appConfig.setAppId(GenericConstants.APP_ID_PRE + appId);
					appConfig.setTitle(appConfig.getType() == 1 ? "account"
							: "alipay");
					appConfig.setCreateDt(new Date());
					if (!StringUtils.isBlank(appConfig.getValue())) {
						appConfigsDao.save(appConfig);
					}
				}
			}
		}
	}

	@Override
	public void delConfigs(String[] keys, Integer appId) {
		appConfigsDao.delConfigs(keys, GenericConstants.APP_ID_PRE + appId);
	}
}
